<?php
declare(strict_types=1);

namespace ExpressionEngine\LexicalAnalysisEngine;

use Contract\Exceptions\LogicException;

class LexicalAnalysisTag
{
    public function replaceTag(string $expression, int $startIndex, int $length, string $tagId, int $index): string
    {
        $tag = str_pad($this->getTag($tagId, $index), $length, ' ');
        return substr($expression, 0, $startIndex) . $tag . substr($expression, $startIndex + $length);
    }

    protected function getTag(string $tagId, int $index): string
    {
        return sprintf('<%s,%s>', $tagId, $index);
    }

    public function isTag(string $tag): bool
    {
        return boolval(preg_match('/^<([A-Z]{1}),(\d+)>$/', $tag));
    }

    /**
     * @param string $tag
     * @return array
     * @throws LogicException
     */
    public function parseTag(string $tag): array
    {
        if (!preg_match('/^<([A-Z]{1}),(\d+)>$/', $tag, $matches)) {
            throw new LogicException('tag:' . $tag . ' is not valid');
        }
        $data = [];
        $data['tag_id'] = $matches[1];
        $data['index'] = $matches[2];
        return $data;
    }
}